<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>大文件分片上传</title>
</head>
<body>
<h1>大文件分片上传测试</h1>
<input type="file" id="myFile">
<div id="log"></div>
</body>

<script src="http://120.25.227.106:8081/statics/js/jquery-2.0.0.min.js"></script>
<script>
    let api = "http://120.25.227.106:8082";

    let myFile = document.getElementById("myFile");
    myFile.onchange = function () {
        let ws = new WebSocket("ws://127.0.0.1:9504");
        ws.onopen = function (e) {
            log('已连接上！');
        };

        ws.onmessage = function (e) {
            log("收到服务器消息:" + e.data + "'\n");
            let file = myFile.files[0];
            let filename = file.name;

            if (e.data == 'connect ok') {
                log('开始上传文件: ' + filename);
            }

            if (e.data == 'upload success') {
                log('上传完成');
                //ws.close();
            } else {

                let filesize = file.size;
                let length = 1024 * 1024 * 0.5;
                let total_number = Math.ceil(filesize / length);
                let start = 0; // 分片的初始位置
                let end = length; // 分片的结束位置
                for (let i = 1; i <= total_number; i++) {
                    let obj = {
                        "name": filename,
                        "type": 1
                    }

                    let reader = new FileReader();
                    // 这里开始分片，并且把每一个分片上传到服务器
                    let blob = file.slice(start, end); // 得到一个分片
                    reader.readAsArrayBuffer(blob);
                    //reader.readAsBinaryString(blob);
                    reader.onload = function (e) {
                        let arrBuf = e.target.result;
                        ws.send(arrBuf);
                        log('正在上传分片' + i + '数据...');
                    };

                    start = end; // 调整下一个分片的起始位置
                    end = start + length; // 调整下一个分片的结束位置
                    if (end > file.size) {
                        end = file.size; // 这里对最后的一个分片结束位置进行调整
                    }
                }
            }
        };

        ws.onclose = function () {
            console.log('连接已关闭！');
            log('连接已关闭！');
        }
    };

    //在消息框中打印内容
    function log(text) {
        $("#log").append(text + "<br/>");
    }
</script>
</html>